//
//  AnnouncementViewController.m
//  CMVRFForIOS
//
//  Created by HailongHan on 15/4/19.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "AnnouncementViewController.h"
#import <TPKeyboardAvoidingTableView.h>
#import "DefaultStyleTableViewCell.h"
#import "UserProfileData.h"
#import <MBProgressHUD.h>
#import "PostData.h"
#import "NoticeTableViewCell.h"
#import "PublishNoticeViewController.h"
#import "NoticeViewController.h"
#import "MJRefresh.h"

@interface AnnouncementViewController (){
    MBProgressHUD *HUD;
    NSUInteger beginIndex;
    NSUInteger endIndex;
}

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *dataSource;

@end

@implementation AnnouncementViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self loadData];
}

#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"公告管理";
    
    //适配iOS7uinavigationbar遮挡tableView的问题
    if(IS_IOS7){
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    //自定义完成选择按钮
    UIBarButtonItem *saveBtn = [[UIBarButtonItem alloc] initWithTitle:@"添加" style:UIBarButtonItemStyleDone target:self action:@selector(addOneNotice)];
    self.navigationItem.rightBarButtonItem = saveBtn;
    
    self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:[UIView frameWithOutNavTab] style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self refreshData];
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    
    [self.view addSubview:self.tableView];
}


#pragma mark - 数据处理
- (void)initData {
    self.dataSource = [NSMutableArray new];
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
}

- (void)loadData {
    [self loadAllNoticesBegin:beginIndex andEnd:endIndex];
}

- (void)refreshData {
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
    [self loadAllNoticesBegin:beginIndex andEnd:endIndex];
    
}

- (void)loadMoreData {
    // 马上进入刷新状态
    [self.tableView.mj_footer beginRefreshing];
    beginIndex = self.dataSource.count;
    endIndex = beginIndex + LIST_PAGE_ITEM_COUNTS - 1;
    [self loadAllNoticesBegin:beginIndex andEnd:endIndex];
}


- (void)loadAllNoticesBegin:(NSInteger)si andEnd:(NSInteger)ei {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:[NSNumber numberWithInteger:si] forKey:@"si"];
    [param setValue:[NSNumber numberWithInteger:ei]forKey:@"ei"];
    [param setValue:[NSNumber numberWithInt:1] forKey:@"os"]; //1: 仅返回自己发布的公告 0: 返回自己和上级公司发布的公告
    
    [HttpClient getWithUrl:HTTP_GET_ALL_NOTICES token:[[AccountManager manager]token] paramDic:param resultClass:[PostData class] success:^(PostData *obj) {
        if (si == 0) {
            //下拉刷新
            [self.tableView.mj_header endRefreshing];
            [self.dataSource removeAllObjects];
        }
        else {
            //上拉加载更多
            [self.tableView.mj_footer endRefreshing];
        }
        
        if (obj.getPostResult != nil && obj.getPostResult.count > 0) {
            [self.dataSource addObjectsFromArray:obj.getPostResult];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        if (si == 0) {
            //下拉刷新
            [self.tableView.mj_header endRefreshing];
        }
        else {
            //上拉加载更多
            [self.tableView.mj_footer endRefreshing];
        }
        CMLog(@"获取公告失败：%@", error);
    }];
}

- (void)deleteOneNotice:(PostData *)data {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:data.guidId forKey:@"id"];
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.labelText = @"删除公告中...";
    
    [HttpClient deleteWithUrl:HTTP_DELETE_ONE_NOTICE token:[[AccountManager manager]token] paramDic:param resultClass:[PostData class] success:^(PostData *obj) {
        //成功
        [HUD setHidden:YES];
        [self.dataSource removeObject:data];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [HUD setHidden:YES];
        CMLog(@"设置用户认证数据失败：%@", error);
    }];
}

- (void)addOneNotice {
    PublishNoticeViewController *view = [PublishNoticeViewController new];
    view.publishType = KKPublish_Notice;
    [self.navigationController pushViewController:view animated:YES];
}

#pragma mark - 切换事件
-(void)switchView
{
    [self.tableView reloadData];
    //    if (_segmentControl.selectedSegmentIndex == 0) {
    //        [self.tableView reloadData];
    //    } else if (_segmentControl.selectedSegmentIndex == 1) {
    //
    //    }
}

#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NoticeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NoticeCell"];
    if (cell == nil) {
        cell = [[NoticeTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"NoticeCell"];
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    PostData *item = [self.dataSource objectAtIndex:indexPath.row];
    [cell setTitle:item.title andDetail:item.content andFrom:item.from andDate:[DateTools getChYearMonthDay:item.time]];
    [cell setNewNoticeFlag: NO];
    
    //滑动按钮
    cell.rightUtilityButtons = [self rightButtons];
    cell.delegate = self;
    cell.tag = indexPath.row;
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NoticeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"NoticeCell"];
    if (cell == nil) {
        cell = [[NoticeTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"NoticeCell"];
    }
    return [cell getHeight];
}

-(NSArray *)rightButtons {
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor redColor] title:@"删除"];
    return rightUtilityButtons;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //反选
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    PostData *item = [self.dataSource objectAtIndex:indexPath.row];
    
    NoticeViewController *view = [NoticeViewController new];
    view.viewType = KKView_Notice;
    view.titleStr = item.title;
    NSString *formatTime = [DateTools getChYearMonthDay:item.time];
    view.fromAndDateStr = [NSString stringWithFormat:@"%@  %@", item.from, formatTime];
    view.guidId = item.guidId;
    view.contentStr = item.content;
    [self.navigationController pushViewController:view animated:YES];
}


#pragma mark - 滑动按钮代理协议
/**
 *  右侧滑动按钮点击事件
 *
 *  @param cell  单元cell
 *  @param index 下标
 */
-(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index{
    switch (index) {
        case 0:{
            PostData *item = [self.dataSource objectAtIndex:cell.tag];
            [self deleteOneNotice:item];
            break;
        }
            
        default:
            break;
    }
    [cell hideUtilityButtonsAnimated:YES];
}


/**
 *  滑动的时候把其他的隐藏掉
 *
 *  @param cell cell
 *
 *  @return 隐藏其他的cell
 */
-(BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell{
    return YES;
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
